package com.hethongviet.preventingmachine.helps.db;

import java.util.ArrayList;
import java.util.List;

import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.models.Relay;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class RelaySQLite
{
	public static final String TABLE_NAME = "relays";

	public static final String COLUMN_ID_DB = "idDB";

	public static final String COLUMN_INDEX = "_index";
	public static final String COLUMN_NAME = "name";
	public static final String COLUMN_IS_ON = "is_active";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;
	private String[] _allColumns = { COLUMN_ID_DB,

	COLUMN_INDEX, COLUMN_NAME, COLUMN_IS_ON };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "

			+ COLUMN_INDEX + " integer, " + COLUMN_NAME + " text, "
			+ COLUMN_IS_ON + " integer";

	public RelaySQLite(Context context, String databaseName)
	{
		_dbHelper = new MySQLiteHelper(context, null, null, databaseName);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	private boolean dataExist(Relay relay, Cursor cursor)
	{
		if (cursor == null)
		{
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
		{
			long idDB = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
			if (idDB == relay.getIdDB()) return true;
		}
		return false;
	}

	/**
	 * @param relay
	 * @return row id -1: insert fail
	 */
	public long insert(Relay relay)
	{
		Utils.debug("insert -- " + TABLE_NAME + " : " + relay.getName());
		open();

		Cursor cursor = _database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE " + COLUMN_ID_DB + " = " + relay.getIdDB(), null);

		long temp = -1;
		if (!dataExist(relay, cursor))
		{
			Utils.debug("insert 1111111111111 INSERT");
			/* Insert to database */
			/* Insert new */
			Cursor cursorInsert = _database.rawQuery("INSERT INTO "
					+ TABLE_NAME + "(" + COLUMN_INDEX + ", " + COLUMN_NAME
					+ ", " + COLUMN_IS_ON + ") values( ?, ?,?)",

			new String[] { relay.getIndex() + "", relay.getName(),
					relay.isOn() ? "1" : "0" });

			cursorInsert.moveToFirst();
			if (!cursorInsert.isAfterLast()) temp = cursorInsert.getLong(cursorInsert.getColumnIndex(COLUMN_ID_DB));

			cursorInsert.close();
		}
		else
		{
			Utils.debug("insert 1111111111111 update");
			ContentValues contentValues = new ContentValues();
			contentValues.put(COLUMN_INDEX, relay.getIndex());
			contentValues.put(COLUMN_NAME, relay.getName());
			contentValues.put(COLUMN_IS_ON, relay.isOn() ? "1" : "0");

			temp = _database.update(TABLE_NAME, contentValues, COLUMN_ID_DB
					+ " = " + relay.getIdDB(), null);
		}
		cursor.close();
		close();
		return temp;
	}

	public void updateStatus(Relay relay)
	{
		open();

		Utils.debug(TABLE_NAME + " update = " + relay.getIndex());
		/* Update to database */

		ContentValues contentValues = new ContentValues();
		contentValues.put(COLUMN_IS_ON, (relay.isOn() ? "1" : "0"));
		_database.update(TABLE_NAME, contentValues, COLUMN_ID_DB + " = \'"
				+ relay.getIdDB() + "\'", null);
		close();
	}

	public void deleteAll()
	{
		open();

		System.out.println(TABLE_NAME + " deleted all");
		// _database.rawQuery("DELETE FROM " + TABLE_NAME, null); not work
		// _database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE 1", null);
		_database.delete(TABLE_NAME, "1", null);
		close();
	}

	public List<Relay> getAll()
	{
		open();

		List<Relay> listRelays = new ArrayList<Relay>();

		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			Relay relay = cursorToRelay(cursor);
			listRelays.add(relay);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listRelays;
	}

	private Relay cursorToRelay(Cursor cursor)
	{
		Relay relay = new Relay();
		relay.setIdDB(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		relay.setIndex(cursor.getInt(cursor.getColumnIndex(COLUMN_INDEX)));
		relay.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
		relay.setOn(cursor.getInt(cursor.getColumnIndex(COLUMN_IS_ON)) == 1);
		return relay;
	}

	public final boolean isTableExist()
	{
		open();

		boolean isExist = false;
		Cursor cursor = _database.rawQuery(
				"select DISTINCT tbl_name from sqlite_master where tbl_name = '"
						+ TABLE_NAME + "'", null);
		isExist = cursor != null && cursor.getCount() > 0;

		cursor.close();
		close();

		return isExist;
	}
}
